package cn.edu.baiyunu.myapplication.ui.screens.profile.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.edu.baiyunu.myapplication.data.model.Category
import cn.edu.baiyunu.myapplication.data.model.SavingsGoal
import cn.edu.baiyunu.myapplication.data.model.Settings
import cn.edu.baiyunu.myapplication.data.repository.CategoryRepository
import cn.edu.baiyunu.myapplication.data.repository.SavingsGoalRepository
import cn.edu.baiyunu.myapplication.data.repository.SettingsRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject
import java.util.UUID

/**
 * 个人资料页面的ViewModel
 */
@HiltViewModel
class ProfileViewModel @Inject constructor(
    private val settingsRepository: SettingsRepository,
    private val categoryRepository: CategoryRepository,
    private val savingsGoalRepository: SavingsGoalRepository
) : ViewModel() {

    // 用户设置状态
    private val _settings = MutableStateFlow<Settings?>(null)
    val settings: StateFlow<Settings?> = _settings

    // 分类管理相关状态
    private val _expenseCategories = MutableStateFlow<List<Category>>(emptyList())
    private val _incomeCategories = MutableStateFlow<List<Category>>(emptyList())
    
    // 储蓄目标相关状态
    private val _savingsGoals = MutableStateFlow<List<SavingsGoal>>(emptyList())
    
    // 分类管理UI状态
    val profileUiState = combine(
        _settings,
        _expenseCategories,
        _incomeCategories,
        _savingsGoals
    ) { settings, expenseCategories, incomeCategories, savingsGoals ->
        ProfileUiState(
            settings = settings,
            expenseCategories = expenseCategories,
            incomeCategories = incomeCategories,
            savingsGoals = savingsGoals
        )
    }.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = ProfileUiState()
    )

    init {
        loadSettings()
        loadCategories()
        loadSavingsGoals()
    }

    // 加载用户设置
    private fun loadSettings() {
        viewModelScope.launch {
            settingsRepository.getSettings().collect { userSettings ->
                _settings.value = userSettings ?: Settings()
            }
        }
    }

    // 加载分类数据
    private fun loadCategories() {
        viewModelScope.launch {
            categoryRepository.getExpenseCategories().collect { categories ->
                _expenseCategories.value = categories
            }
        }
        
        viewModelScope.launch {
            categoryRepository.getIncomeCategories().collect { categories ->
                _incomeCategories.value = categories
            }
        }
    }
    
    // 加载储蓄目标
    private fun loadSavingsGoals() {
        viewModelScope.launch {
            savingsGoalRepository.getAllSavingsGoals().collect { goals ->
                _savingsGoals.value = goals
            }
        }
    }

    // 更新用户名
    fun updateUsername(username: String) {
        viewModelScope.launch {
            settingsRepository.updateUsername(username)
        }
    }

    // 添加分类
    fun addCategory(name: String, icon: String, type: String) {
        viewModelScope.launch {
            val newCategory = Category(
                id = UUID.randomUUID().toString(),
                name = name,
                icon = icon,
                type = type,
                orderIndex = if (type == "expense") _expenseCategories.value.size else _incomeCategories.value.size
            )
            categoryRepository.addCategory(newCategory)
        }
    }

    // 更新分类
    fun updateCategory(categoryId: String, name: String, icon: String) {
        viewModelScope.launch {
            // 先找到原分类
            val category = _expenseCategories.value.find { it.id == categoryId }
                ?: _incomeCategories.value.find { it.id == categoryId }
                
            category?.let {
                val updatedCategory = it.copy(
                    name = name,
                    icon = icon
                )
                categoryRepository.updateCategory(updatedCategory)
            }
        }
    }

    // 删除分类
    fun deleteCategory(categoryId: String) {
        viewModelScope.launch {
            categoryRepository.deleteCategory(categoryId)
        }
    }
    
    // 添加储蓄目标
    fun addSavingsGoal(name: String, targetAmount: Double, savingRate: Double, icon: String, type: String) {
        viewModelScope.launch {
            val newGoal = SavingsGoal(
                id = UUID.randomUUID().toString(),
                name = name,
                targetAmount = targetAmount,
                savingRate = savingRate,
                icon = icon,
                type = type
            )
            savingsGoalRepository.addSavingsGoal(newGoal)
        }
    }
    
    // 更新储蓄目标
    fun updateSavingsGoal(goalId: String, name: String, targetAmount: Double, savingRate: Double, icon: String, type: String) {
        viewModelScope.launch {
            val goal = _savingsGoals.value.find { it.id == goalId }
            
            goal?.let {
                val updatedGoal = it.copy(
                    name = name,
                    targetAmount = targetAmount,
                    savingRate = savingRate,
                    icon = icon,
                    type = type
                )
                savingsGoalRepository.updateSavingsGoal(updatedGoal)
            }
        }
    }
    
    // 删除储蓄目标
    fun deleteSavingsGoal(goalId: String) {
        viewModelScope.launch {
            savingsGoalRepository.deleteSavingsGoal(goalId)
        }
    }
}

/**
 * 个人资料页面UI状态
 */
data class ProfileUiState(
    val settings: Settings? = null,
    val expenseCategories: List<Category> = emptyList(),
    val incomeCategories: List<Category> = emptyList(),
    val savingsGoals: List<SavingsGoal> = emptyList()
) 